package org.example.loadBalancers;

import org.example.ServiceInstance;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;

@Component
public class RoundLoadBalancer extends LoadBalancer{

    //存每种服务的轮询索引  TODO 存在挤压问题 问题不大 暂不考虑  或者说定时删除冗余的 但稳定之后一般不用很频繁
    Map<String , Integer>  serviceIndex =new HashMap<>();


    public RoundLoadBalancer() {
        super("round");
    }


    //轮询算法 要维护一个轮询的索引    可能很慢  服务的增删等情况 导致不是100%轮询 这个没办法
    @Override
    public ServiceInstance getServiceInstance(String serviceName) {

        //他底层是一个LinkedHashSet
        LinkedHashSet<ServiceInstance> serviceInstances =
                (LinkedHashSet<ServiceInstance>) serviceContext.getServices(serviceName);

        //如果没有服务 就返回null
        if(serviceInstances.isEmpty()){
            return null;
        }

        //先找到索引 如果没有就创建一个
        if(!serviceIndex.containsKey(serviceName)){
            serviceIndex.put(serviceName,0);
        }
        int index = serviceIndex.get(serviceName);


        //转数组先
        ServiceInstance[] serviceInstanceArray = serviceInstances.toArray(new ServiceInstance[0]);
        //如果索引超出范围 就重置
        if(index >= serviceInstanceArray.length){
            index = 0;
        }

        serviceIndex.put(serviceName,index+1);
        return serviceInstanceArray[index];
    }


    //根据服务容器来初始化轮询索引
    @PostConstruct
    public void init(){
        super.init();
       serviceContext.getAllServices().forEach((serviceName, serviceInstances) -> serviceIndex.put(serviceName,0));

    }
}
